﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //发货服务
    public class ProductDeliveryController : Controller
    {
        private readonly IProductDeliveryBillService operationServiceImpl = ServiceLocator.Instance.GetService<IProductDeliveryBillService>();	

        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id, string orgCode, bool isConfirm = false)
        {
            ProductDeliveryBillDto billModel = operationServiceImpl.GetProductDeliveryBill(id);
            ViewBag.IsConfirm = isConfirm;
            ViewBag.orgCode = orgCode;
            return View(billModel);
        } 
        #endregion

        #region 保存和提交统一入口
         [NoAuthorizated("AddAndConfirm")]
         [HttpPost]
        public ActionResult AddAndConfirm(ProductDeliveryBillDto roductInBillDto)
        {
            bool isConfirm =Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
             //保存(或更新)
            string actionResult = AddPrivate(roductInBillDto);
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                if (tempId.Equals(Guid.Empty))//有超过库存数量的单据
                {
                    return Content("-3");
                }
                roductInBillDto.Id = tempId;
            }
            else
            {
                return Content(actionResult.ToString());
            }
          //提交
          if (isConfirm)
          {
              if (roductInBillDto.Id == null || roductInBillDto.Id.Equals(Guid.Empty))//记录已存在
              {
                 
              }

              if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))//记录已存在
              {
                  var orgCode = Request.Form["HidOrgCode"] ?? "";
                  if (!string.IsNullOrEmpty(orgCode))
                  {
                      Confirm(roductInBillDto.Id, orgCode);//提交
                  }
              }
          }
          return Content("9");
         }
        #endregion
        #region 添加发货
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode, Guid? id)
        {

            ProductDeliveryBillDto billModel = null;
           
            if (id == null || !id.HasValue)
            {
                var NO = new BusinessBillNoCreator().CreateDeliveryNextNO();

                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                var wareHouse = initSysData.Values.FirstOrDefault();
               // var org = initSysData.Keys.FirstOrDefault();


                billModel = new ProductDeliveryBillDto
                {
                    DeliveryNo = NO,
                    StorehouseName = wareHouse.StorehouseName,
                    StorehouseID = wareHouse.Id
                    //DeliveryorName = org.Name,
                    //DeliveryorID=org.Id
                };

                #region 新厂和老厂的收货单位都为成都,现在其它的只能是深圳
                if (orgCode.Trim().ToUpper() == SystemConfig.LaoChangCode.ToString().Trim().ToUpper() || orgCode.Trim().ToUpper() == SystemConfig.XinChangCode.ToString().Trim().ToUpper())
                {
                    var cdinitSysData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ChengDuCode);//初始化默认组织机构和仓库
                    var cdorg = cdinitSysData.Keys.FirstOrDefault();
                    billModel.DeliveryName = cdorg.Name;
                    billModel.DeliveryID = cdorg.Id;
                }
                else
                {
                    var cdinitSysData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ShengZhenCode);//初始化默认组织机构和仓库
                    var cdorg = cdinitSysData.Keys.FirstOrDefault();
                    billModel.DeliveryName = cdorg.Name;
                    billModel.DeliveryID = cdorg.Id;
                }
	            #endregion


                ViewBag.BillId = "";

               
            }
            else
            {
                Guid billId ;
                Guid.TryParse(id.ToString(),out billId);
                billModel = operationServiceImpl.GetProductDeliveryBill(billId);
               ViewBag.BillId = billId.ToString();
            }
            ViewBag.TempId = Guid.Empty;
            ViewBag.orgCode = orgCode.Trim();
            #region 获取仓库ID
            if (orgCode.Trim().ToUpper() == SystemConfig.LaoChangCode.ToString().Trim().ToUpper() || orgCode.Trim().ToUpper() == SystemConfig.XinChangCode.ToString().Trim().ToUpper())
            {
                IProductService wareHoseServiceImpl = ServiceLocator.Instance.GetService<IProductService>();

                var wareHourses = wareHoseServiceImpl.GetAllStorehouse(orgCode);
                Guid wareHourseId = Guid.Empty;
                if (wareHourses != null)
                {
                    ViewBag.WareHourseId = wareHourses.First().Id;
                }
            }
            #endregion

            billModel.DeliveryDate = DateTime.Today;
            return View(billModel);
            
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProductDeliveryBillDto roductInBillDto)
        {
            
            #region 弹出框数据获取
            var model = new ProductCheckBillModel();
            //仓库ID
            var whId=model.GetRequestFormValues(this.HttpContext,"StorehouseName_val");
            if(!Guid.Empty.Equals(whId))
            {
              roductInBillDto.StorehouseID =whId;
            }
            ViewBag.WareHourseId = roductInBillDto.StorehouseID;
            var DeliveryorId = model.GetRequestFormValues(this.HttpContext, "DeliveryorName_val");
            if (!Guid.Empty.Equals(DeliveryorId))
            {
                roductInBillDto.DeliveryorID = DeliveryorId;
            }
            var SenderId = model.GetRequestFormValues(this.HttpContext, "SenderName_val");
            if (!Guid.Empty.Equals(SenderId))
            {
                roductInBillDto.SenderID = SenderId;
            }
           
            #endregion
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
	        #endregion
            #region 明细行数据处理


            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ProductDeliveryBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item =>
            {
                item.ProductDeliveryBillID = checkId;
                if (item.ID == null || item.ID.Equals(Guid.Empty))
                {
                    item.ID = Guid.Empty;
                }
            });

	        #endregion

            #region 验证输出


            if (roductInBillDto.StorehouseID == null || Guid.Empty.Equals(roductInBillDto.StorehouseID))
            {
                ModelState.AddModelError("StorehouseID","仓库不能为空！");
            }
            if (roductInBillDto.SenderID == null || Guid.Empty.Equals(roductInBillDto.SenderID))
            {
                ModelState.AddModelError("SenderID", "发货人不能为空！");
            }
            if (roductInBillDto.DeliveryorID == null || Guid.Empty.Equals(roductInBillDto.DeliveryorID))
            {
                ModelState.AddModelError("DeliveryorID", "送货人不能为空！");
            }

            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    bool isValidateStock = true;
                    #region 厂里发出货，空库存数据写入
                    
                    
                    string orgCode = Request.Form["HidOrgCode"] ?? "";
                    if (orgCode.Trim().ToUpper() == SystemConfig.LaoChangCode.ToString().Trim().ToUpper() || orgCode.Trim().ToUpper() == SystemConfig.XinChangCode.ToString().Trim().ToUpper())
                    {
                        isValidateStock = false;
                        var wareHourseId =Guid.Parse( Request.Form["WareHourseId"]);
                        var stockList = new List<StockDto>();


                        detailItems.Each(t =>
                        {
                            if (t.ID == null || t.ID.Equals(Guid.Empty))
                            {
                                stockList.Add(
                                    new StockDto
                                    {
                                        DownCount = 0f,
                                        ProductID = t.StockID,
                                        StorehouseID = wareHourseId,
                                        StockCount = 0f,
                                        SumMoney = 0m,
                                        UpCount = 0f
                                    }
                                    );
                            }
                        });
                        if (stockList.Count() != 0)
                        {
                            IStockService stockServiceImpl = ServiceLocator.Instance.GetService<IStockService>();
                          var stockDtos=  stockServiceImpl.AddStockEmpty(stockList);
                          if (stockDtos != null && stockDtos.Count() != 0)
                          {
                              stockDtos.Each(t =>
                              {
                                  foreach (var item in detailItems)
                                  {
                                      if (t.ProductID == item.StockID && t.StorehouseID == wareHourseId)
                                      {
                                          item.StockID = t.ID;
                                          break;
                                      }
                                  }
                              });
                          }
                        }
                   
                    }
                    #endregion
                    #region 操作正常发货数据
                    
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        roductInBillDto.UpdateDate = DateTime.Now;
                        roductInBillDto.UpdateID = roductInBillDto.CreateID;
                        this.operationServiceImpl.UpdateProductDeliveryBill(roductInBillDto, detailItems, isValidateStock);
                    }
                    else
                    {
                        var id = operationServiceImpl.AddProductDeliveryBill(roductInBillDto, detailItems, isValidateStock);
                        return Content(id.ToString());
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    return Content("-1");
                }
                return Content("9");
            }
            
            return Content("0");
        }

        private string AddPrivate(ProductDeliveryBillDto roductInBillDto)
        {

            #region 弹出框数据获取
            var model = new ProductCheckBillModel();
            //仓库ID
            var whId = model.GetRequestFormValues(this.HttpContext, "StorehouseName_val");
            if (!Guid.Empty.Equals(whId))
            {
                roductInBillDto.StorehouseID = whId;
            }
            var DeliveryorId = model.GetRequestFormValues(this.HttpContext, "DeliveryorName_val");
            if (!Guid.Empty.Equals(DeliveryorId))
            {
                roductInBillDto.DeliveryorID = DeliveryorId;
            }
            var SenderId = model.GetRequestFormValues(this.HttpContext, "SenderName_val");
            if (!Guid.Empty.Equals(SenderId))
            {
                roductInBillDto.SenderID = SenderId;
            }

            #endregion
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
            #endregion
            #region 明细行数据处理


            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ProductDeliveryBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return ("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item =>
            {
                item.ProductDeliveryBillID = checkId;
                if (item.ID == null || item.ID.Equals(Guid.Empty))
                {
                    item.ID = Guid.Empty;
                }
            });

            #endregion

            #region 验证输出


            if (roductInBillDto.StorehouseID == null || Guid.Empty.Equals(roductInBillDto.StorehouseID))
            {
                ModelState.AddModelError("StorehouseID", "仓库不能为空！");
            }
            if (roductInBillDto.SenderID == null || Guid.Empty.Equals(roductInBillDto.SenderID))
            {
                ModelState.AddModelError("SenderID", "发货人不能为空！");
            }
            if (roductInBillDto.DeliveryorID == null || Guid.Empty.Equals(roductInBillDto.DeliveryorID))
            {
                ModelState.AddModelError("DeliveryorID", "送货人不能为空！");
            }

            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    bool isValidateStock = true;
                    #region 厂里发出货，空库存数据写入


                    string orgCode = Request.Form["HidOrgCode"] ?? "";
                    if (orgCode.ToString().Trim().ToUpper() == SystemConfig.LaoChangCode.ToString().Trim().ToUpper() || orgCode.ToString().Trim().ToUpper() == SystemConfig.XinChangCode.ToString().Trim().ToUpper())
                    {
                        isValidateStock = false;

                        var wareHourseId = Guid.Parse(Request.Form["WareHourseId"]);
                        var stockList = new List<StockDto>();


                        detailItems.Each(t =>
                        {
                            if (t.ID == null || t.ID.Equals(Guid.Empty))
                            {
                                stockList.Add(
                                    new StockDto
                                    {
                                        DownCount = 0f,
                                        ProductID = t.StockID,
                                        StorehouseID = wareHourseId,
                                        StockCount = 0f,
                                        SumMoney = 0m,
                                        UpCount = 0f
                                    }
                                    );
                            }
                        });
                        if (stockList.Count() != 0)
                        {
                            IStockService stockServiceImpl = ServiceLocator.Instance.GetService<IStockService>();
                            var stockDtos = stockServiceImpl.AddStockEmpty(stockList);
                            if (stockDtos != null && stockDtos.Count() != 0)
                            {
                                stockDtos.Each(t =>
                                {
                                    foreach (var item in detailItems)
                                    {
                                        if (t.ProductID == item.StockID && t.StorehouseID == wareHourseId)
                                        {
                                            item.StockID = t.ID;
                                            break;
                                        }
                                    }
                                });
                            }
                        }

                    }
                    #endregion
                    #region 操作正常发货数据

                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        roductInBillDto.UpdateDate = DateTime.Now;
                        roductInBillDto.UpdateID = roductInBillDto.CreateID;
                        var id = this.operationServiceImpl.UpdateProductDeliveryBill(roductInBillDto, detailItems, isValidateStock);
                        return id.ToString();
                    }
                    else
                    {
                        var id = operationServiceImpl.AddProductDeliveryBill(roductInBillDto, detailItems, isValidateStock);
                        return id.ToString();
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    return "-1";
                }
                return "9";
            }

            return "0";
        }
        #endregion
        #region 收货确认
        //收货确认UI操作
         [NoAuthorizated("AuditIndex")]
        public ActionResult AuditIndex()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        //收货确认持久化操作
         [NoAuthorizated("Audit")]
        public ActionResult Audit(string orgCode,Guid billId)
        {
            if (!billId.Equals(Guid.Empty))
            {
                var op = ImportConfirmToProductIn(billId.ToString());
                return Content(op ? "9" : "0");
            }
            return Content("0");
        }
         //收货确认(打回)持久化操作
         [NoAuthorizated("UnAudit")]
         public ActionResult UnAudit(string orgCode, Guid billId)
         {
             if (!billId.Equals(Guid.Empty))
             {
                 var op = UnImportConfirmToProductIn(billId.ToString());
                 return Content(op ? "9" : "0");
             }
             return Content("0");
         }
         private bool UnImportConfirmToProductIn(string ids)
         {
             if (ids.Trim().Length > 0)
             {
                 string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                 var guidIds = new List<Guid>();
                 arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                 try
                 {
                     operationServiceImpl.UnAudit(guidIds, UserModel.GetLoginUserId(this.HttpContext), new BusinessBillNoCreator().CreateInNextNO(), SystemConfig.BuinessBillNOLength);
                 }
                 catch (Exception)
                 {
                     return false;
                 }
             }
             return true;
         }

        private bool ImportConfirmToProductIn(string ids)
        {
            if (ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                try
                {
                    operationServiceImpl.Audit(guidIds, UserModel.GetLoginUserId(this.HttpContext), new BusinessBillNoCreator().CreateInNextNO(), SystemConfig.BuinessBillNOLength);
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }
        #endregion
        #region 发货提交
         [NoAuthorizated("Confirm")]
        public ActionResult Confirm(Guid billId, string orgCode)//(string ids)
        {
            if (billId!=null&&!Guid.Empty.Equals(billId))
            {
                try
                {
                    if (orgCode == SystemConfig.XinChangCode || orgCode == SystemConfig.LaoChangCode)//厂里发货，提交不需要更新库存
                    {
                        operationServiceImpl.ConfirmProductDeliveryNoStock(new List<Guid> { billId }, UserModel.GetLoginUserId(this.HttpContext));
                    }
                    else
                    {
                        operationServiceImpl.ConfirmProductDelivery(new List<Guid> { billId }, UserModel.GetLoginUserId(this.HttpContext));
                    }
                }
                catch (Exception)
                {
                    return Content("0");
                }
            }
             return Content("9");
        }
        #endregion
        #region 更新至库存
        public ActionResult UpdateToStock(Guid billId, string ids)
        {

            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.UpdateToStock(billId, guidIds);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {
            
            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                if (!guidIds[0].Equals(Guid.Empty))
                {
                    operationServiceImpl.ConvertProductDeliveryBillDeleteState(billId, guidIds);
                }
                return Content("9");
            }
            else
            {
                operationServiceImpl.ConvertProductDeliveryBillDeleteState(billId);
                return Content("9");
            }
            
            return Content("0");
        }
        #endregion
        #region 获取发货列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfDatas")]
        public ActionResult GetJsonOfDatas()//bool? isConfirm
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            bool isConfirm = true;
            var productBills = operationServiceImpl.GetProductDeliveryBills(1, 100, false, null);
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u =>
                {
                    u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                    u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                    u.AffirmStateName = u.AffirmState > 0 ? "已确认" : "未确认";
                    if (u.AffirmDate.HasValue) { u.AffirmDate = DateTime.Parse(u.AffirmDate.Value.ToString("yyyy-MM-dd")); }
                    return u;
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + productBills.Count()+ "\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetProductDeliveryBills(this.HttpContext));
        }
        #region 选择销售过该客户的产品信息
         [NoAuthorizated("GetSellProducts")]
        public ActionResult GetSellProducts(Guid clientId,string orgCode)
        {
            ViewBag.OrgCode = orgCode;
            ViewBag.ClientId = clientId;
            return View();
        }
        
        [NoAuthorizated("GetJsonOfSellProducts")]
        public ActionResult GetJsonOfSellProducts()//获得销售过的该客户的商品信息
        {
            return Content(new BLLQuery().GetProductAllotProducts(this.HttpContext));
        }
        #endregion
        /// <summary>
        /// 根据发货ID，获得发货所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfBillDetails")]
        public ActionResult GetJsonOfBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var billDetails = operationServiceImpl.GetProductDeliveryBillDetails(billId).Where(p => p.Deleted == 0).ToList();
            if (billDetails != null && billDetails.Count() != 0)
            {
                var jsonResult = billDetails.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails.Count() + "\"}";
                return Content(target);
            }
            */
            #endregion
            if (!billId.Equals(Guid.Empty))
            {
                return Content(new BLLQuery().GetProductDeliveryDetails(billId));

            }
            else
            {
                return Content("");
            }
        }
        #endregion
        #region 打印收货确认单据
        [NoAuthorizated("Print")]
        public ActionResult Print(Guid billId)
        {
            var billAndDetails = operationServiceImpl.GetBillAndDetails(billId); //获得主表数据和从表数据
            var printModel = new ProductDeliveryBillPrint
            {
                ProductDeliveryBillDto = billAndDetails.Keys.FirstOrDefault(),
                ProductDeliveryBillDetailDtos = billAndDetails.Values.FirstOrDefault()
            };


            //if (printModel.ProductDeliveryBillDetailDtos != null && printModel.ProductDeliveryBillDetailDtos.Count() != 0)
            //{
               
            //    foreach (var t in printModel.ProductDeliveryBillDetailDtos)
            //    {
            //        if (t.Deleted != 1)
            //        {
            //            printModel.ProductOutBillDto.SellMoney += Math.Round(((decimal)t.SellAmount * t.SellPrice), 2);
            //        }
            //    }
            //}
            return View(printModel);
            //return Content(" 这个是测试数据");
        }

        #endregion

        #region 深圳 收货确认
        public ActionResult SZIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("Index");
        }
        public ActionResult SZAuditIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("AuditIndex");
        }
        #endregion
        #region 新厂 收货确认
        public ActionResult XCIndex()
        {
            ViewBag.orgCode = SystemConfig.XinChangCode;
            return View("Index");
        }
        #endregion
        #region 老厂 收货确认
        public ActionResult LCIndex()
        {
            ViewBag.orgCode = SystemConfig.LaoChangCode;
            return View("Index");
        }
        #endregion
    }
}
